<?php
declare (strict_types=1);

namespace app\api\controller;

use app\api\model\Logistics;
use Predis\Client;

class LogisticsRoamController
{
    protected $redis;

    public function __construct()
    {
        $this->redis = new Client([
            'scheme' => config('redis.scheme'),
            'host' => config('redis.host'),
            'port' => config('redis.port'),
            'cache' => config('redis.cache'),
            'password' => config('redis.password')
        ]);
    }

    /**
     * 查询订单的物流流转信息接口
     */
    public function getOrderLogisticsInfo()
    {
        //1、接收订单id
        $logisticsId = input('order_id');

        //2、验证数据
        if (!isset($logisticsId) || !is_numeric($logisticsId)) return json(['code' => '4005', 'msg' => '请选择要查询的商品物流', 'data' => '']);

        //3、查询订单的物流信息
        $logisticsInfo = Logistics::where('order_id', $logisticsId)->find();
        //$orderInfo = (new Orders())->find($logisticsInfo->order_id);

        if (empty($logisticsInfo)) return json(['code' => 4006, 'msg' => '订单不存在', 'data' => '']);

        //4、查询redis缓存中是否有物流信息
        $redisLogisticsInfo = $this->redis->get($logisticsInfo->logistics_no);
        //5、判断结果 有
        if (!empty($redisLogisticsInfo)) return json(['code' => '200', 'msg' => '查询成功', 'data' => $redisLogisticsInfo]);
        //无 调用阿里云快递单号接口
        $localLogisticsInfo = Gocurl($logisticsInfo->logistics_no, $logisticsInfo->type);
        //判断查询结果
        if ($localLogisticsInfo['status'] != 200) return json(['code' => $localLogisticsInfo['status'], 'msg' => $localLogisticsInfo['message'], 'data' => '']);
        //并存储到redis缓存中
        $this->redis->set($logisticsInfo->logistics_no, json_encode($localLogisticsInfo));

        return json(['code' => 200, 'msg' => '查询成功', 'data' => $localLogisticsInfo]);
    }

    /**
     * 订单物流流转状态修改
     */
    public static function logisticsTimeUp()
    {
        $redis = new Client([
            'scheme' => config('redis.scheme'),
            'host' => config('redis.host'),
            'port' => config('redis.port'),
            'cache' => config('redis.cache'),
            'password' => config('redis.password')
        ]);
        //获取所有未完成的物流
        $logisticsData = Logistics::where('status', 0)->select()->toArray();
        foreach ($logisticsData as $k => $v) {
            //获取缓存
            $upBeforeLogisticsData = $redis->get($v['logistics_no']);
            if (!empty($upBeforeLogisticsData)) {
                //更新缓存中订单物流
                $upAfterLogisticsData = Gocurl($v['logistics_no'], $v['type']);
                if ($upAfterLogisticsData['status'] != 200) {
                    echo $v['logistics_no'] . $upAfterLogisticsData['message'];
                } else {
                    //并重新存储
                    $redis->set($v['logistics_no'], json_encode($upAfterLogisticsData));
                    echo $v['logistics_no'] . '更新成功';
                }
            }
        }
    }
}

